package com.dtx.zhuge.spring.clazz;

import com.dtx.zhuge.spring.anno.Autowired;
import com.dtx.zhuge.spring.anno.Component;
import com.dtx.zhuge.spring.anno.ComponentScan;
import com.dtx.zhuge.spring.anno.Scope;
import com.dtx.zhuge.spring.inter.BeanNameAware;
import com.dtx.zhuge.spring.inter.BeanPostProcessor;
import com.dtx.zhuge.spring.inter.InitializingBean;

import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class DtxApplicationContext {

    private Class configClass;

    private ConcurrentHashMap<String,Object> singletonObjects = new ConcurrentHashMap<>(); // 单例池
    private ConcurrentHashMap<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>(); //
    // 存放BeanPostProcessor实例
    private  List<BeanPostProcessor> beanPostProcessorList = new ArrayList<>();

    public DtxApplicationContext(Class configClass) {

        this.configClass = configClass;

        // 解析配置类
        // ComponentScan注解-->扫描路径-->扫描
        scan(configClass);

        for (Map.Entry<String,BeanDefinition> entry : beanDefinitionMap.entrySet()) {
            String beanName = entry.getKey();
            BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
            if (beanDefinition.getScope().equals("singleton")) {
                Object bean = createBean(beanName,beanDefinition); // 单例Bean
                singletonObjects.put(beanName,bean);
            }
        }
    }

    public Object createBean(String beanName,BeanDefinition beanDefinition){
        Class clazz = beanDefinition.getClazz();
        try {
            Object instance = clazz.getDeclaredConstructor().newInstance();

            //依赖注入

            for (Field declaredField : clazz.getDeclaredFields()) {
                if (declaredField.isAnnotationPresent(Autowired.class)) {
                    declaredField.setAccessible(true);
                    Object bean = getBean(declaredField.getName());
                    declaredField.set(instance,bean);
                }
            }

            // Aware回调
            if (instance instanceof BeanNameAware) {
                ((BeanNameAware) instance).setBeanName(beanName);
            }

            // bean初始化前的操作
            for (BeanPostProcessor beanPostProcessor : beanPostProcessorList) {
                 instance = beanPostProcessor.postProcessBeforeInitialization(instance, beanName);
            }

            // 初始化
            if (instance instanceof InitializingBean) {
                try {
                    ((InitializingBean) instance).afterPropertiesSet();
                }catch (Exception e){
                    e.printStackTrace();
                }

            }

            // BeanPostProcessor
            // 初始化后
            for (BeanPostProcessor beanPostProcessor : beanPostProcessorList) {
                instance = beanPostProcessor.postProcessAfterInitialization(instance, beanName);
            }

            return instance;
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        return null;
    }

    private void scan(Class configClass) {
        ComponentScan componentScanAnnotation = (ComponentScan) configClass.getDeclaredAnnotation(ComponentScan.class);
        String path = componentScanAnnotation.value();
        path=path.replace(".","/");
        System.out.println("path："+path);
        //扫描
        // Bootstrap--->jre/lib
        // Ext------->jre/ext/lib
        // App------->classpath------>
        ClassLoader classLoader = DtxApplicationContext.class.getClassLoader();//app
        URL resource = classLoader.getResource(path);  //拿到全部路径
        File file = new File(resource.getFile());
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (File f : files) {
                String fileName = f.getAbsolutePath();
                if (fileName.endsWith(".class")) {
                    String className = fileName.substring(fileName.indexOf("com"),fileName.indexOf(".class"));  //截取字符串
                    className = className.replace("\\",".");  //改为com.dtx

                    try {
                        Class<?>  clazz = classLoader.loadClass(className);
                        if (clazz.isAnnotationPresent(Component.class)) {
                            // 表示当前这个类是一个Bean
                            // 解析类-->BeanDefinition
                            // BeanDefinition

                            // 当前对象是否实现了BeanPostProcessor接口
                            if (BeanPostProcessor.class.isAssignableFrom(clazz)) {
                                BeanPostProcessor instance = (BeanPostProcessor) clazz.getDeclaredConstructor().newInstance();
                                beanPostProcessorList.add(instance);
                            }

                            Component componentAnnotation = clazz.getDeclaredAnnotation(Component.class);
                            String beanName = componentAnnotation.value();
                            //如果只是Component注解，需要把类名的第一个大写字母改成小写字母
                            if ("".equals(beanName)) {
                                beanName = clazz.getName().substring(clazz.getName().lastIndexOf(".") + 1);
                                beanName = String.valueOf(beanName.charAt(0)).toLowerCase() + beanName.substring(1);
                            }

                            BeanDefinition beanDefinition = new BeanDefinition();
                            beanDefinition.setClazz(clazz);
                            if (clazz.isAnnotationPresent(Scope.class)) {
                                Scope scopeAnnotation = clazz.getDeclaredAnnotation(Scope.class);
                                beanDefinition.setScope(scopeAnnotation.value());
                            }else {
                                beanDefinition.setScope("singleton");
                            }
                            // 存放到 beanDefinitionMap里
                            beanDefinitionMap.put(beanName,beanDefinition);
                        }
                    } catch (ClassNotFoundException | NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {
                        e.printStackTrace();
                    }

                }

            }
        }
    }

    public Object getBean(String beanName){
        if (beanDefinitionMap.containsKey(beanName)) {
            BeanDefinition beanDefinition =  beanDefinitionMap.get(beanName);
            if (beanDefinition.getScope().equals("singleton")) {
                Object o = singletonObjects.get(beanName);
                return o;
            }else {
                // 创建bean对象
                Object bean = createBean(beanName,beanDefinition);
                return bean;
            }

        }else {
            //不存在对应的Bean
            throw new RuntimeException("不存在对应的bean");
        }

    }
}
